from flask import render_template,redirect,url_for,session,request,jsonify
from flask_login import login_user, login_required, logout_user, current_user

from bson.objectid import ObjectId

from model.sprint import SprintDao
from service.project import ProjectService
from service.sprint import SprintService, SprintForm

from controller import app

import json


    
    
@app.route("/get_sprints")
@app.route("/get_sprints", methods=['GET','POST'])
#@login_required
def get_sprints():
    """ This is an Ajax handler
    """
    sprints = []
    if 'project_id' in request.values.keys():
        project_id = request.values['project_id']
        serv = SprintService()
        sprints = serv.get_sprints({'project_id':project_id})

    return jsonify(sprints=json.dumps(sprints))


""" The following are Ajax handlers
"""
@app.route('/submit_sprint', methods=['GET','POST'])
#@login_required
def submit_sprint():
    form = SprintForm()
    if form.is_submitted():
        if form.has_error():
            return jsonify(errors=json.dumps(form.errors))
        else:
            service = SprintService()
            service.submit_sprint(form.input, form.mode)
            return jsonify(errors=[])
   
@app.route('/get_sprint')
@app.route('/get_sprint', methods=['GET','POST'])
@login_required
def get_sprint():
    sid = request.values['sid']
    serv = SprintService()
    sprint = serv.get_sprint(sid)
    return jsonify(sprint=json.dumps(sprint))

@app.route('/delete_sprints')
@app.route('/delete_sprints', methods=['GET','POST'])
def delete_sprints():
    sid = request.values['sprint_id']
    serv = ProjectService()
    serv.delete_sprint(sid)
    _sprints = serv.get_sprints()

    return jsonify(sprints=json.dumps(_sprints))  